<template>
	<view class="container">


		<view class="example">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">
				<uni-forms-item label="单号" label-width="90px" name="serialNo">
					<uni-easyinput v-model="valiFormData.serialNo" disabled placeholder="请输入单号" />
				</uni-forms-item>
				<uni-forms-item label="日期" label-width="90px" name="handleTime">
					<uni-datetime-picker type="datetime" disabled v-model="valiFormData.handleTime" />
				</uni-forms-item>

				<uni-forms-item label="构筑物名称" label-width="90px" name="structureName">
					<uni-easyinput v-model="valiFormData.structureName" disabled placeholder="请输入构筑物名称" />
				</uni-forms-item>

				<uni-forms-item label="设备名称" label-width="90px" required name="deviceName">
					<uni-easyinput v-model="valiFormData.deviceName" disabled placeholder="请输入设备名称" />
				</uni-forms-item>
				<uni-forms-item label="故障描述" label-width="90px" name="faultDetails">
					<uni-easyinput type="textarea" v-model="valiFormData.faultDetails" disabled placeholder="请输入故障描述" />
				</uni-forms-item>
				<uni-forms-item label="故障图片" label-width="90px" name="">
					<image v-if="valiFormData.faultImgPath" :src="'http://211.103.114.94:2081/camera/IoReadImageByPath?path='+valiFormData.faultImgPath" style="width: 120rpx;height: 120rpx;margin-top: 15rpx;" class="image1" @click="handleZoom('http://211.103.114.94:2081/camera/IoReadImageByPath?path='+valiFormData.faultImgPath)"></image>
						<image v-if="!valiFormData.faultImgPath" src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png" style="width: 120rpx;height: 120rpx;margin-top: 15rpx;" class="image1" @click="handleZoom('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png')"></image>
					
				</uni-forms-item>






				<uni-forms-item  label="审批结果" label-width="90px" name="approve">
					<uni-easyinput type="textarea" v-model="valiFormData.approve" disabled placeholder="请输入审批结果" />
				</uni-forms-item>
				<uni-forms-item  label="维修人" label-width="90px" required name="repairPerson">
					<uni-data-select v-model="valiFormData.repairPerson" :localdata="userlist" disabled
						@change="change3"></uni-data-select>
				</uni-forms-item>

				<uni-forms-item  label="处理情况" label-width="90px" name="dealDetails">
					<uni-easyinput type="textarea" v-model="valiFormData.dealDetails" disabled placeholder="请输入处理情况" />
				</uni-forms-item>
				<uni-forms-item  label="维修耗材" label-width="90px" name="maintenanceText">
					<uni-easyinput type="textarea" v-model="valiFormData.maintenanceText" disabled placeholder="请输入保养内容" />
				</uni-forms-item>
				<uni-forms-item  label="维修结束图片" label-width="90px" name="repairImgPath">
					<!-- <uni-file-picker limit="9" title="最多选择9张图片"></uni-file-picker> -->
					
						<image v-if="valiFormData.repairImgPath" :src="'http://211.103.114.94:2081/camera/IoReadImageByPath?path='+valiFormData.repairImgPath" style="width: 120rpx;height: 120rpx;margin-top: 15rpx;" class="image1" @click="handleZoom('http://211.103.114.94:2081/camera/IoReadImageByPath?path='+valiFormData.repairImgPath)"></image>
							<image v-if="!valiFormData.repairImgPath" src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png" style="width: 120rpx;height: 120rpx;margin-top: 15rpx;" class="image1" @click="handleZoom('https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png')"></image>
						
				</uni-forms-item>
				<uni-forms-item  label="验收人" label-width="90px" required name="verifyPerson">
					<uni-data-select v-model="valiFormData.verifyPerson" disabled :localdata="userlist"
						@change="change3"></uni-data-select>
				</uni-forms-item>


				<uni-forms-item  label="验收结果" label-width="90px" name="verify">
					<uni-easyinput type="textarea" v-model="valiFormData.verify" placeholder="请输入验收结果" />
				</uni-forms-item>




			</uni-forms>
			<button type="primary"  @click="submit('valiForm')">提交</button>
		</view>




	</view>
</template>
<script>
	import {
		queryPersonInfo,createProduceRepair
	} from "@/api/index"

	// 以下路径需根据项目实际情况填写
	import {
		pathToBase64,
		base64ToPath
	} from '../../js_sdk/mmmm-image-tools/index.js'
	import {
		getToken,
		
		setToken,
		removeToken
	} from '@/utils/auth'
	export default {
		data() {
			return {
				status: null,

				// 单选数据源
				scheduleFlags: [{
					text: '是',
					value: '是'
				}, {
					text: '否',
					value: '否'
				}],
				source: [{
					text: '是',
					value: '是'
				}, {
					text: '否',
					value: '否'
				}],
				fileList: [],
				imageStyles: {
					width: 90,
					height: 90,
				},
				// uni.chooseImage值，从相册选择，拍摄
				sourceType: ['album', 'camera'],
				// 校验表单数据
				valiFormData: {
					"type": "维修",
					"handleTime": null,
					"stationType": "",
					"stationName": "",
					"structureName": "",
					"deviceName": "",
					"faultDetails": "",
					"faultImgPath": "",
					"repairGroups": "",
					"dealDetails": "",
					"material": "",
					"verify": ""
				},
				// 校验规则
				rules: {
					lastTime: {
						rules: [{
							required: true,
							errorMessage: '上次保养时间不能为空'
						}]
					}
				},
				userlist: [],imgList:[],imgList1:[]



			}
		},
		onLoad: function(option) {
			this.valiFormData = JSON.parse(option.item);
			console.info('aaaaaaaaaaa', this.valiFormData)
			const originalDateStr = this.valiFormData.handleTime;
			//this.valiFormData.faultImgPath = this.valiFormData.faultImgPath.toString()
			// 创建一个新的Date对象
			const originalDate = new Date(originalDateStr);

			// 将日期转换为 "yyyy-MM-dd HH:mm:ss" 格式
			const year = originalDate.getFullYear();
			const month = String(originalDate.getMonth() + 1).padStart(2, '0');
			const day = String(originalDate.getDate()).padStart(2, '0');
			const hours = String(originalDate.getHours()).padStart(2, '0');
			const minutes = String(originalDate.getMinutes()).padStart(2, '0');
			const seconds = String(originalDate.getSeconds()).padStart(2, '0');

			const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			console.log("this.$Route.query", option);
			this.valiFormData.handleTime = formattedDateTime
			this.status = this.valiFormData.status
		},
		onReady() {
			this.getUserlist();
		},
		methods: {handleZoom(imgSrc) {console.info('aaaaa',imgSrc)
				// 使用uni的previeImage方法实现图片预览放大
				this.imgList = []
				this.imgList.push(imgSrc)
				uni.previewImage({
					current: imgSrc, // 当前显示图片的http链接
					urls: this.imgList  // 需要预览的图片http链接列表
				});
			},
			change3(e) {
				console.log("e2:", e);
			},
			getUserlist() {
				let form={};
				queryPersonInfo(form).then(response => {
					console.info(response)
					response.forEach((item) => {
						let a = {};
						a.value = item.personName
						a.text = item.personName
						this.userlist.push(a)

					});
				})
			},
			openImg() { //预览图片	
				let that = this;
				uni.showLoading({
					title: "加载中..."
				})
				var arr = [];
				base64ToPath(this.bimg)
					.then(path => {
						console.log('----', path);
						uni.hideLoading()
						arr[0] = path;
						uni.previewImage({
							current: 0,
							urls: arr
						});
					})
					.catch(error => {
						// 图片加载失败
						uni.hideLoading()
					})

			},

			submit(ref) {

				console.log('success', this.$refs[ref]);
				this.$refs[ref].validate().then(res => {
					console.log('success', this.valiFormData);
					res.type = '维修';
					if(this.status =='正在审批'){
						res.status = '正在处理';
					}else{
						res.status = '已完成';
					}
					
					console.info("pppppppppp", this.fileList)
					if (this.fileList.length > 0) {
						res.repairImgPath = this.fileList[0].url;
					}
					createProduceRepair(res).then(response => {
						console.info('ccccccc', response)
						if (response == '') {
							uni.showToast({
								title: `提交成功`
							})
							uni.navigateTo({
								url: '/pages/index/repair'
							})
						} else {
							uni.showToast({
								title: `提交失败`,
								icon: 'fail'
							})
						}


					})

				}).catch(err => {
					console.log('err', err);
				})
			},
			imgPreview(base64) {
				base64ToPath(base64)
					.then(path => {
						console.log(path)
						var arr = [];
						arr[0] = path
						uni.previewImage({
							indicator: "none",
							loop: false,
							urls: arr,
						})
					})
					.catch(error => {
						console.error(error)
					})

			},
			getIamge(path, item) {
				var token = getToken();
				uni.request({
					url: 'http://211.103.114.94:2081/app/IoReadImageByPath',
					method: 'GET',
					responseType: 'arraybuffer', // 指定响应类型为arraybuffer，以便处理文件流
					data: {
						token: token,
						app_version: 'your_app_version',
						path: path
					},
					success: function(res) {
						// 将获取到的文件流转换为base64格式
						var base64 = uni.arrayBufferToBase64(res.data);
						// 将base64格式的文件展示为图片
						// 假设imgElement是用于展示图片的img标签
						item.faultImgPath = 'data:image/png;base64,' + base64; // 假设文件类型为png，根据实际情况修改
					},
					fail: function(error) {
						console.log('请求失败', error);
					}
				});
			},
			// 获取上传状态
			select(e) {
				// 获取本地存储中的认证令牌
				const accessToken = uni.getStorageSync('accessToken');
				console.log('选择文件：', e)
				// 解决file对象取值问题
				// 微信小程序上传-需要微信临时提供临时地址
				const file = e;
				var token = getToken();
				// 处理每张选中的图片
				uni.uploadFile({
					url: 'http://211.103.114.94:2081/app/upload',
					filePath: file.tempFilePaths[0],
					// 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
					name: 'fileinput',
					formData: {
						token: token,
						app_version: 'your_app_version'
					},

					// 成功函数
					success: (res) => {
						console.log('上传成功', res.data);
						// uni.uploadFile返回来的结果默认是JSON格式字符串，需要用JSON.parse转换成js对象
						console.log('上传数据转换', JSON.parse(res.data));
						let uploaddata = JSON.parse(res.data)
						let x = {}
						// 下面3个值是uni-app规定的一个不能少
						x.url = uploaddata.data

						x.extname = file.tempFiles[0].name;
						x.name = file.tempFiles[0].extname;
						console.log('上传成功', x);
						this.fileList.push(x)
					},
					// 失败提示用户重新上传
					fail: error => {
						console.log('失败', error);
					}
				})
			},
			// 获取上传进度
			progress(e) {
				// 没有上传空间，不会执行 
				console.log('上传进度：', e)
			},
			// 上传成功
			success(e) {
				// 没有上传空间，不会执行 
				console.log('上传成功')
			},
			// 上传失败
			fail(e) {
				// 没有上传空间，不会执行 
				console.log('上传失败：', e)
			},
			// 删除
			deletea(e) {
				console.log('删除图片', e);
			},
		}
	}
</script>
<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>